package com.qiche.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.qiche.aspect.Result;
import com.qiche.mapper.RoleMapper;
import com.qiche.model.Role;
import com.qiche.model.RoleResources;
import com.qiche.service.RoleService;
import com.qiche.mapper.RoleResourcesMapper;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import tk.mybatis.mapper.entity.Example;

@Service("roleService")
public class RoleServiceImpl extends BaseService<Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleResourcesMapper roleResourcesMapper;

    @Override
    public List<Role> queryRoleListWithSelected(Integer uid) {
        return roleMapper.queryRoleListWithSelected(uid);
    }

    @Override
    public List<Role> queryAdminRoleListWithSelected(Integer uid) {
        return roleMapper.queryAdminRoleListWithSelected(uid);
    }

    @Override
    public PageInfo<Role> selectByPage(Role role, int page, int limit) {
        //int page = start/length+1;
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        //分页查询
        if (role.getMerchantId() != null && role.getMerchantId() != 0) {
            criteria.andEqualTo("merchantId", role.getMerchantId());
        }else{
            criteria.andIsNull("merchantId");
        }
        PageHelper.startPage(page, limit);
        List<Role> rolesList = selectByExample(example);
        return new PageInfo<>(rolesList);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public Result delRole(Integer roleid) {
        //删除角色
       int deleteCount1= mapper.deleteByPrimaryKey(roleid);
        //删除角色资源
        Example example = new Example(RoleResources.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleid",roleid);
        int deleteCount2=roleResourcesMapper.deleteByExample(example);
        if(deleteCount1>0){
            return Result.createBySuccessMessage("删除成功");
        }
        return Result.createByErrorMessage("删除失败");


    }

    @Override
    public Role queryRoleByUserId(Integer userId) {
        return roleMapper.queryRoleByUserId(userId);
    }

    @Override
    public List<Role> selectRolesByMerchantId(Long  merchantId) {

        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if(merchantId!=null){
            criteria.andEqualTo("merchantId",merchantId);
        }
        return roleMapper.selectByExample(example);

    }
}
